using UnityEngine;
using System.Collections;
using OpenCvSharp;
using System.Runtime.InteropServices;
using System.IO;

[RequireComponent(typeof(Renderer))]
public class DisplayDepth : MonoBehaviour {
	
	public DepthWrapper dw;
	private CvColor color_red;
	private Texture2D tex;
	
	// Use this for initialization
	void Start () {
		tex = new Texture2D(320,240,TextureFormat.ARGB32,false);
		renderer.material.mainTexture = tex;
		color_red = new CvColor(255,0,0);
		
	}
	
	// Update is called once per frame1
	void Update () {
		if (dw.pollDepth())
		{
			tex.SetPixels32(mipmapImg(convertDepthToColor(dw.depthImg),640,480));
			//tex.SetPixels32(convertPlayersToCutout(dw.segmentations));
			tex.Apply(false);
//			byte[] pngfile = tex.EncodeToPNG();
//			File.WriteAllBytes("U:/navjotg/My Documents/TestingOpenCV/Resources/saveImage.png",pngfile);
//			IplImage img = Cv.LoadImage("U:/navjotg/My Documents/TestingOpenCV/Resources/saveImage.png");
//			IplImage imgGray = img.Clone();
//			Cv.CvtColor(img,imgGray,ColorConversion.RgbaToGray);
//			imgGray.SaveImage("U:/navjotg/My Documents/TestingOpenCV/Resources/saveImage2.png");
//			//byte[] grayPng = File.ReadAllBytes("U:/navjotg/My Documents/TestingOpenCV/Resources/saveImage2.png");
//			tex = (Texture2D)Resources.Load("U:/navjotg/My Documents/TestingOpenCV/Resources/saveImage2.png");			
		}
	}
	
	private Color32[] convertDepthToColor(short[] depthBuf)
	{
		Color32[] img = new Color32[depthBuf.Length];
		for (int pix = 0; pix < depthBuf.Length; pix++)
		{
			img[pix].r = (byte)(depthBuf[pix] >> 8);
			img[pix].g = (byte)(depthBuf[pix] >> 8);
			img[pix].b = (byte)(depthBuf[pix] >> 8);
			
		}
		return img;
	}
	
	
	private Color32[] convertPlayersToCutout(bool[,] players)
	{
		Color32[] img = new Color32[640*480];
		for (int pix = 0; pix < 320*240; pix++)
		{
			if(players[0,pix]|players[1,pix]|players[2,pix]|players[3,pix]|players[4,pix]|players[5,pix])
			{
				img[pix].a = (byte)255;
			} else {
				img[pix].a = (byte)0;
			}
		}
		return img;
	}
	
	private Color32[] mipmapImg(Color32[] src, int width, int height)
	{
		int newWidth = width / 2;
		int newHeight = height / 2;
		Color32[] dst = new Color32[newWidth * newHeight];
		for(int yy = 0; yy < newHeight; yy++)
		{
			for(int xx = 0; xx < newWidth; xx++)
			{
				int TLidx = (xx * 2) + yy * 2 * width;
				int TRidx = (xx * 2 + 1) + yy * width * 2;
				int BLidx = (xx * 2) + (yy * 2 + 1) * width;
				int BRidx = (xx * 2 + 1) + (yy * 2 + 1) * width;
				dst[xx + yy * newWidth] = Color32.Lerp(Color32.Lerp(src[BLidx],src[BRidx],.5F),
				                                       Color32.Lerp(src[TLidx],src[TRidx],.5F),.5F);
			}
		}
		return dst;
	}
}
